'use strict'

let {Boke, Op } = require('../modul');
/*
let Boke = [
    {
        id: 1,
        headline: '论EF Core的自我修养',
        abstract: 'Core的自我修养',
        content: '论EF Core的自我修养',
        classify: '.net',
        author:'In Cerry',
        time:2022-04-06-08.47
    },
    {
        id: 2,
        headline: 'DDD',
        abstract: 'DDD',
        content: '论EF DDD',
        classify: '技术',
        author:'In DDD',
        time:2022-05-06-08.47
    },
]
*/

let fn_list = async (ctx, next) => {

    let keyword = ctx.request.query.keyword || '';

    if (keyword) {

        let list;
        
        list = await Boke.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { productName: keyword },
                    { price: isNaN(keyword) ? 0 : keyword },
                    { stockNum: isNaN(keyword) ? 0 : keyword },
                    { supplier: keyword },
                ]
            },
            order: ['id']
        })

        ctx.body = {
            code: 1000,
            data: list
        }
    } else {
        let list = await Products.findAll();

        ctx.body = {
            code: 1000,
            data: list
        }
    }
};

let fn_getById = async (ctx, next) => {
    let id = ctx.request.parms.id;

    let list = await Boke.findByPk(id)

    if (list) {
        ctx.body = {
            code: 1000,
            data: list,
            msg: '查询完成'
        }
    } else {
        ctx.body = {
            code: 400,
            data: '',
            msg: '查询失败'
        }
    }
}

let fn_post = async (ctx, next) => {
    let obj = ctx.request.body;

    await Boke.create(obj);

    ctx.body = {
        code: 1000,
        data: "",
        msg: '增加成功'
    }
}

let fn_put = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;

    let boke = await Boke.findByPk(id);

    if (boke) {
        Boke.update(obj, {
            where: {
                id: id
            }
        })
        ctx.body = {
            code: 1000,
            data: "",
            msg: "修改成功"
        }

    } else {
        ctx.body = {
            code: 400,
            data: "",
            msg: '修改失败'
        }
    }
}

let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id;

    let boke = await Boke.findByPk(id);

    if (boke) {
        Boke.dextroy({
            where: {
                id: id
            }
        })
        tx.body = {
            code: 1000,
            data: "",
            msg: "删除完成"
        }

    } else {
        ctx.body = {
            code: 400,
            data: "",
            msg: '删除失败'
        }
    }
}


module.exports = {
    'get /boke': fn_list,
    'get /boke/:id': fn_getById,
    'post /boke': fn_post,
    'put /boke/:id': fn_put,
    'delete /boke/:id': fn_delete
}